import { defineStore } from 'pinia';

import { userLogin } from '@/api/user';
import { LoginRequest, LoginResponse } from '@/api/user/types';
import { BaseResponse } from '@/http/request';
import {
    setToken,
    removeToken,
    setRefreshToken,
    removeRefreshToken,
} from '@/utils/auth';

interface UserState {
    username: string;
    roles?: string[];
}

export const useUserStore = defineStore(
    'user',
    () => {
        const userInfo = ref<UserState>({
            username: '',
            roles: [],
        });
        const storeUserLogin: (
            data: LoginRequest,
        ) => Promise<BaseResponse<LoginResponse>> = async function (
            data: LoginRequest,
        ): Promise<BaseResponse<LoginResponse>> {
            console.log(data);
            return userLogin(data).then((res) => {
                setToken(res.data.accessToken);
                setRefreshToken(res.data.refreshToken);
                userInfo.value.username = res.data.username;
                userInfo.value.roles = res.data.roles;
                return res;
            });
        };
        const storeUserLogout: () => Promise<void> =
            function (): Promise<void> {
                return new Promise((resolve) => {
                    removeToken();
                    removeRefreshToken();
                    userInfo.value = {
                        username: '',
                        roles: [],
                    };
                    resolve();
                });
            };
        return {
            userInfo,
            storeUserLogin,
            storeUserLogout,
        };
    },
    {
        persist: {
            key: 'user',
            storage: localStorage,
            pick: ['userInfo.username', 'userInfo.roles'],
        },
    },
);
